import React, { useState } from 'react'
import ProTable, { ProColumns } from '@ant-design/pro-table';
import { queryRule } from '../../pages/goods/goods-list/service';
import { get } from 'lodash';
import { Modal } from 'antd'
import { ModalFuncProps } from 'antd/lib/modal/index.d'

interface SelectGoodsPorps extends ModalFuncProps {
  goodsIds?: Array<any>
  type?: 'checkbox' | 'radio'
}
export default (props: SelectGoodsPorps) => {
  const {
    width = 1000,
    goodsIds = [],
    type = 'checkbox',
    onOk,
    onCancel
  } = props;

  const [currentSelectedRowKeys, setCurrentSelectedRowKeys] = useState<Array<any>>(goodsIds)
  const [goodsList, setGoodsList] = useState([]);

  const columns: ProColumns<any>[] = [
    {
      title: '商品名称',
      dataIndex: 'name',
    },
    {
      title: '图片',
      dataIndex: 'main_pic',
      render: (val) => val && <img alt="商品图片" src={val} style={{ width: 50, height: 50 }} />,
    },
    // {
    //   title: '是否上架',
    //   dataIndex: 'online',
    //   render: (v) => (v === 1 ? '是' : '否'),
    // },
    {
      title: '分类',
      dataIndex: 'category.name',
      render: (v, record) => get(record, ['category', 'name'], '-'),
    },
  ];
  return (
    <Modal
      visible={true}
      width={width}
      onOk={() => onOk(goodsList.filter(it => currentSelectedRowKeys.includes(it.id)))}
      onCancel={onCancel}
    >
      <ProTable<any>
        headerTitle="商品列表"
        rowKey="id"
        toolBarRender={false}
        request={async (params) => {
          const { data } = await queryRule({
            page: params?.current || 1,
            pageSize: params?.pageSize,
          });
          data.data = data.list;
          setGoodsList(data.list);
          return data;
        }}
        rowSelection={{
          type,
          selectedRowKeys: currentSelectedRowKeys,
          preserveSelectedRowKeys: true,
          onChange: (selectedRowKeys) => {
            setCurrentSelectedRowKeys(selectedRowKeys)
          }
        }
        }
        columns={columns}
      />
    </Modal>
  )
}
